package flc.ast.activity;

import android.app.Dialog;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.blankj.utilcode.util.ToastUtils;
import com.blankj.utilcode.util.UriUtils;
import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import flc.ast.BaseAc;
import flc.ast.R;
import flc.ast.adapter.AlbumChildAdapter;
import flc.ast.adapter.PhoneAlbumAdapter;
import flc.ast.bean.PhoneAlbumBean;
import flc.ast.databinding.ActivityRecordBinding;
import flc.ast.utils.AlbumManager;
import flc.ast.utils.MyMediaLoader;
import io.reactivex.rxjava3.core.ObservableEmitter;
import stark.common.basic.event.EventStatProxy;
import stark.common.basic.utils.IntentUtil;
import stark.common.basic.utils.RxUtil;

public class RecordActivity extends BaseAc<ActivityRecordBinding> {

    public static String sFilePath;
    private PhoneAlbumAdapter mPhoneAlbumAdapter;
    private AlbumManager mInstance;
    private boolean isEdit;
    private boolean hasSelectAll;
    private int totalIndex;
    private Dialog myDeleteDialog,myDetailDialog;
    private ImageView imageView;

    @Override
    protected int onCreate() {
        return R.layout.activity_record;
    }

    @Override
    protected void initView() {
        EventStatProxy.getInstance().statEvent1(this, mDataBinding.event1Container);
        mDataBinding.ivRecordBack.setOnClickListener((v) -> onBackPressed());
        mDataBinding.ivRecordEdit.setOnClickListener(this);
        mDataBinding.tvAllsel.setOnClickListener(this);
        mDataBinding.tvShare.setOnClickListener(this);
        mDataBinding.tvDelete.setOnClickListener(this);

        mInstance = AlbumManager.getInstance();
        mInstance.addListener(iDataChangeListener);

        mDataBinding.rvRecordList.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false));
        mPhoneAlbumAdapter = new PhoneAlbumAdapter();
        mDataBinding.rvRecordList.setAdapter(mPhoneAlbumAdapter);
        mPhoneAlbumAdapter.setEdit(isEdit);
        mPhoneAlbumAdapter.addChildClickViewIds(R.id.ivPhoneAlbumSelector);
        mPhoneAlbumAdapter.setOnItemClickListener(this);
        mPhoneAlbumAdapter.setOnItemChildClickListener(this);
        //删除弹框
        deleteDialog();
        //详情弹框
        detailDialog();
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()){
            case R.id.ivRecordEdit://编辑
                if (isEdit){
                    mDataBinding.llRecordBottom.setVisibility(View.GONE);
                    isEdit=false;
                    mPhoneAlbumAdapter.setEdit(isEdit);
                }else {
                    mDataBinding.llRecordBottom.setVisibility(View.VISIBLE);
                    isEdit=true;
                    mPhoneAlbumAdapter.setEdit(isEdit);
                }
                mPhoneAlbumAdapter.notifyDataSetChanged();
                break;
            case R.id.tvAllsel://全选
                hasSelectAll = !hasSelectAll;
                setHasSelectAll(hasSelectAll);
                break;
            case R.id.tvShare://分享
                share();
                break;
            case R.id.tvDelete://删除
                myDeleteDialog.show();
                break;
            //删除弹框
            case R.id.ivDialogDeleteConfirm:
                delete();
                myDeleteDialog.dismiss();
                break;
            case R.id.ivDialogDeleteCancel:
                myDeleteDialog.dismiss();
                break;
            //详情弹框
            case R.id.ivDialogRecordCancel:
                myDetailDialog.dismiss();
                break;
        }
    }

    @Override
    protected void onItemClickCallback(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        if (adapter instanceof PhoneAlbumAdapter) {
            switch (view.getId()) {
                case R.id.ivPhoneAlbumSelector:
                    PhoneAlbumBean item = mPhoneAlbumAdapter.getItem(position);
                    item.setSelected(!item.isSelected());
                    for (PhoneAlbumBean.ClassBean classBean : item.getClassBeanList()) {
                        classBean.setSelected(item.isSelected());
                    }
                    mPhoneAlbumAdapter.notifyDataSetChanged();

                    if (item.isSelected()) {
                        mInstance.addPhoneAlbum(item.getClassBeanList());
                    } else {
                        mInstance.deletePhoneAlbum(item.getClassBeanList());
                    }
                    break;
            }
        } else if (adapter instanceof AlbumChildAdapter) {
            AlbumChildAdapter albumChildAdapter = (AlbumChildAdapter) adapter;
            PhoneAlbumBean.ClassBean item = albumChildAdapter.getItem(position);
            if (!isEdit) {
//                ImageViewer.load(item.getPath())//要加载的图片数据，单张或多张
//                        .imageLoader(new GlideImageLoader())//加载器，imageLoader必须配置，目前内置的有GlideImageLoader或PicassoImageLoader，也可以自己实现
//                        .start(this, view);//activity or fragment, 跳转时的共享元素视图
                Glide.with(mContext).load(item.getPath()).into(imageView);
                myDetailDialog.show();
                return;
            }
            item.setSelected(!item.isSelected());
            albumChildAdapter.notifyDataSetChanged();

            boolean isSelectAll = true;
            for (PhoneAlbumBean.ClassBean classBean : albumChildAdapter.getData()) {
                if (!classBean.isSelected()) {
                    isSelectAll = false;
                    break;
                }
            }
            PhoneAlbumBean phoneAlbumBean = albumChildAdapter.getPhoneAlbumBean();
            phoneAlbumBean.setSelected(isSelectAll);
            mPhoneAlbumAdapter.notifyDataSetChanged();

            if (item.isSelected()) {
                mInstance.addPhoneAlbum(item);
            } else {
                mInstance.deletePhoneAlbum(item);
            }
        }
    }

    @Override
    protected void initData() {
        getData();
    }

    private void share() {
        List<PhoneAlbumBean.ClassBean> phoneAlbumBeans = mInstance.getPhoneAlbumBeans();
        if (phoneAlbumBeans.size() == 0) {
            ToastUtils.showShort(R.string.please_sel_share);
            return;
        }
        List<String> picPathList = new ArrayList<>();
        for (PhoneAlbumBean.ClassBean bean : phoneAlbumBeans) {
            picPathList.add(bean.getPath());
        }
        IntentUtil.shareImagesPath(mContext,picPathList);
    }

    private void delete() {
        List<PhoneAlbumBean.ClassBean> phoneAlbumBeans = mInstance.getPhoneAlbumBeans();
        if (phoneAlbumBeans.size() == 0) {
            ToastUtils.showShort(R.string.please_sel_delete);
            return;
        }
        for (int i = 0; i < mPhoneAlbumAdapter.getData().size(); i++) {
            for (int j = 0; j < mPhoneAlbumAdapter.getData().get(i).getClassBeanList().size(); j++) {
                if (mPhoneAlbumAdapter.getData().get(i).getClassBeanList().get(j).isSelected()) {
                    mContext.getContentResolver().delete(UriUtils.file2Uri(new File(
                            mPhoneAlbumAdapter.getData().get(i).getClassBeanList().get(j).getPath())), null, null);
                    mInstance.deletePhoneAlbum(mPhoneAlbumAdapter.getData().get(i).getClassBeanList().get(j));
                    mPhoneAlbumAdapter.getData().get(i).getClassBeanList().remove(j);
                    j--;
                }
            }
            if (mPhoneAlbumAdapter.getData().get(i).isSelected()) {
                mPhoneAlbumAdapter.getData().remove(i);
                i--;
            }
        }
        mPhoneAlbumAdapter.notifyDataSetChanged();
        getTotalCount();
        if (mPhoneAlbumAdapter.getData().size() == 0) {
            mDataBinding.tvRecordNoData.setVisibility(View.VISIBLE);
            mDataBinding.rvRecordList.setVisibility(View.GONE);
        }
        ToastUtils.showShort(R.string.delete_suc);
    }

    private void getData() {
        RxUtil.create(new RxUtil.Callback<List<PhoneAlbumBean>>() {
            @Override
            public void doBackground(ObservableEmitter<List<PhoneAlbumBean>> emitter) {
                List<PhoneAlbumBean> phoneAlbumBeans = MyMediaLoader.getInstance().loadPicData(true, sFilePath);
                emitter.onNext(phoneAlbumBeans);
            }

            @Override
            public void accept(List<PhoneAlbumBean> phoneAlbumBeanList) {
                if (phoneAlbumBeanList == null || phoneAlbumBeanList.size() == 0) {
                    mDataBinding.tvRecordNoData.setVisibility(View.VISIBLE);
                    mDataBinding.rvRecordList.setVisibility(View.GONE);
                } else {
                    mDataBinding.tvRecordNoData.setVisibility(View.GONE);
                    mDataBinding.rvRecordList.setVisibility(View.VISIBLE);
                }

                mPhoneAlbumAdapter.setList(phoneAlbumBeanList);
                getTotalCount();
            }
        });
    }

    private void getTotalCount() {
        totalIndex = 0;
        for (PhoneAlbumBean phoneAlbumBean : mPhoneAlbumAdapter.getData()) {
            totalIndex = phoneAlbumBean.getClassBeanList().size() + totalIndex;
        }
    }

    public void setHasSelectAll(boolean hasSelectAll) {
        List<PhoneAlbumBean.ClassBean> classBeanList = new ArrayList<>();
        for (PhoneAlbumBean datum : mPhoneAlbumAdapter.getData()) {
            datum.setSelected(hasSelectAll);
            classBeanList.addAll(datum.getClassBeanList());

            for (PhoneAlbumBean.ClassBean classBean : datum.getClassBeanList()) {
                classBean.setSelected(hasSelectAll);
            }
        }
        // 判断是否正在备份中，如果是在备份中，点击取消按钮，将不删除数据，否则在上传中时再进入页面将无法展示正在上传的列表
        if (hasSelectAll) {
            mInstance.addPhoneAlbum(classBeanList);
            mDataBinding.tvAllsel.setText(getString(R.string.cancel_sel));
        } else {
            mInstance.deletePhoneAlbum(classBeanList);
            mDataBinding.tvAllsel.setText(getString(R.string.all_sel));
        }
        mPhoneAlbumAdapter.notifyDataSetChanged();
    }

    private AlbumManager.IDataChangeListener iDataChangeListener = new AlbumManager.IDataChangeListener() {
        @Override
        public void onDataChanged(int currentSize) {
            hasSelectAll = currentSize == totalIndex;
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mInstance != null) {
            mInstance.addListener(iDataChangeListener);
        }
    }

    //删除弹框
    private void deleteDialog() {
        myDeleteDialog = new Dialog(mContext, R.style.DialogStyle);
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.dialog_delete, null);
        myDeleteDialog.setContentView(inflate);
        myDeleteDialog.setCancelable(true);
        Window dialogWindow = myDeleteDialog.getWindow();
        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity(Gravity.BOTTOM);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (dm.widthPixels * 0.9);
        lp.y = 50;
        // 将属性设置给窗体
        dialogWindow.setAttributes(lp);
        ImageView confirm = inflate.findViewById(R.id.ivDialogDeleteConfirm);
        ImageView cancel = inflate.findViewById(R.id.ivDialogDeleteCancel);
        confirm.setOnClickListener(this);
        cancel.setOnClickListener(this);
    }

    //详情弹框
    private void detailDialog() {
        myDetailDialog = new Dialog(mContext, R.style.DialogStyle);
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.dialog_record, null);
        myDetailDialog.setContentView(inflate);
        myDetailDialog.setCancelable(true);
        Window dialogWindow = myDetailDialog.getWindow();
        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity(Gravity.CENTER);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (dm.widthPixels * 0.9);
        // 将属性设置给窗体
        dialogWindow.setAttributes(lp);
        imageView = inflate.findViewById(R.id.ivDialogRecordImg);
        ImageView cancel = inflate.findViewById(R.id.ivDialogRecordCancel);
        cancel.setOnClickListener(this);
    }

}